<template>
  <el-dialog
      :title="props.type === 'add' ? '添加公益服务' : '修改公益服务'"
      v-model="state.visible"
      width="600px"
      @close="clear"
      @open="show"
  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
      <el-form-item label="服务名字" prop="name">
        <el-input type="text" v-model="state.ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="活动封面">
        <el-upload
            :action="uploadImgServer"
            :on-success="handleUrlSuccess"
            list-type="picture"
            :auto-upload="true"
            :show-file-list="false"
        >
          <img v-if="state.ruleForm.cover" :src="state.ruleForm.cover" class="cover" alt="封面"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="简介" prop="summary">
        <el-input type="text" v-model="state.ruleForm.summary"></el-input>
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input type="text" v-model="state.ruleForm.address"></el-input>
      </el-form-item>


      <el-form-item label="内容" prop="content">
        <div id="editor"></div>
      </el-form-item>

      <el-form-item label="开始时间" prop="startDate">
        <el-date-picker
            v-model="state.ruleForm.startDate"
            type="datetime"
            placeholder="Select date and time"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endDate">

        <el-date-picker
            v-model="state.ruleForm.endDate"
            type="datetime"
            placeholder="Select date and time"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>


    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>


</template>

<script setup>

import {reactive, ref, nextTick} from 'vue'
import {useRoute} from 'vue-router'
import {getActivityById, addActivity, updateActivity} from '../service/activityApi.js'
import {uploadImgServer} from "../store/index.js"
import {ElMessage} from 'element-plus'
import E from 'wangeditor'
import {fileUpload} from '../service/minioFileApi.js'

const props = defineProps({
  type: String, // 用于判断是添加还是编辑
  reload: Function // 添加或修改完后，刷新列表页
})

//销毁富文本对象
const clear = () => {
  state.editor.destroy()
}
const show = () => {
  // 富文本编辑器实例创建

  state.editor = new E('#editor')
  //配置上传地址

  // 配置服务器端地址
  state.editor.config.uploadImgServer = uploadImgServer
  state.editor.config.uploadFileName = 'file'
  state.editor.config.uploadImgHooks = {
    customInsert: (insertImgFn, result) => {

      const imgUrl = result.data;
      insertImgFn(imgUrl); // 插入图片
    },
    // 可选：错误处理
    error: (error) => {
      console.error('上传失败:', error);
    }
  };
  // state.editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
  //   const response = await fileUpload(resultFiles[0]);
  //   insertImgFn(response.data)
  // }
  state.editor.config.menus = [
    // 菜单配置
    'head', // 标题
    'bold', // 粗体
    'italic', // 斜体
    'underline', // 下划线
    'link', // 插入链接
    'image', // 插入图片
    'undo', // 撤销
    'redo' // 重复
  ]
  state.editor.create()

}
const formRef = ref(null)
const route = useRoute()
const filelist = ref([])

const state = reactive({
  editor: null,
  visible: false,
  categoryLevel: 1,
  parentId: 0,
  ruleForm: {
    id: '',
    name: '',
    cover: '',
    summary: '',
    content: '',
    startDate: '',
    endDate: '',
    address: ''
  },
  rules: {
    name: [
      {required: true, message: '名称不能为空', trigger: ['change']}
    ],
    cover: [
      {required: true, message: '封面不能为空', trigger: ['change']}
    ],
    summary: [
      {required: true, message: '简介不能为空', trigger: ['change']}
    ],
    address: [
      {required: true, message: '地址不能为空', trigger: ['change']}
    ],
  },
})
// 获取详情
const getDetail = async (id) => {
  const result = await getActivityById(id);
  // 回显表单数据
  state.ruleForm = {
    id: result.data.id,
    name: result.data.name,
    cover: result.data.cover,
    summary: result.data.summary,
    content: result.data.content,
    startDate: result.data.startDate,
    endDate: result.data.endDate,
    address: result.data.address,
  }
  if (state.editor != null) {
    state.editor.txt.html(result.data.content)
  }
}

//删除上传图片
const handleRemove = (file, fileList) => {
  state.ruleForm.cover = ''

}
//上传成功
const handleUrlSuccess = (res) => {
  state.ruleForm.cover = res.data
}

// 开启弹窗
const open = (id) => {
  state.visible = true
  if (id) {
    state.ruleForm.id = id
    // 如果是有 id 传入，证明是修改模式
    getDetail(id)
  } else {
    // 否则为新增模式
    // 新增类目，从路由获取分类 level 级别和父分类 id
    const {level = 1, parent_id = 0} = route.query
    state.ruleForm = {
      id: '',
      name: '',
      cover: '',
      summary: '',
      content: '',
      startDate: '',
      endDate: '',
      address: '',
    }
    state.parentId = parent_id
    state.categoryLevel = level
  }

}

// 关闭弹窗
const close = () => {
  state.visible = false
}


const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.type === 'add') {
        //将内容以html的形式拉下来
        state.ruleForm.content = state.editor.txt.html()
        // 添加方法
        await addActivity(state.ruleForm).then(() => {
          ElMessage.success('添加成功')
          close()
          if (props.reload) props.reload()
        })
      } else {
        // 修改方法
        // 将内容重新覆盖
        state.ruleForm.content = state.editor.txt.html()
        await updateActivity(state.ruleForm).then(() => {
          ElMessage.success('修改成功')
          //富文本编辑器实例销毁，弹窗关闭
          close()
          if (props.reload) props.reload()
        })
      }
    }
  })
}
defineExpose({open, close})
</script>

<style scoped>
.el-upload__tip {
  float: left;
}

.cover {
  border: 1px solid #FFFFFF;
  border-radius: 10px;
  width: 80px;
  height: 80px;
}
</style>